<template>
    <div class="admin-page">
        <div class="page-header">
            <div class="header-title">权限管理</div>
            <el-tabs v-model="activeTab">
                <el-tab-pane label="管理员" name="admin">
                    <div class="table-header">
                        <div class="table-title">管理员列表</div>
                        <div class="table-actions">
                            <el-button type="primary" @click="handleAddAdmin" size="small" icon="el-icon-plus">
                                添加管理员
                            </el-button>
                        </div>
                    </div>
                    <el-table  height="560" :data="adminList" border style="width: 100%;overflow-y: auto"
                              :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                        <el-table-column prop="name" label="登录名"/>
                        <el-table-column prop="username" label="用户名"/>
                        <el-table-column label="创建时间">
                            <template slot-scope="scope">
                                <span>{{ formatTimestamp(scope.row.create_time) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="权限组">
                            <template slot-scope="scope">
                                <span>{{ getGroupName(scope.row.group_id) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="300">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="handleEdit(scope.row)" icon="el-icon-edit">
                                    编辑
                                </el-button>
                                <el-button type="text" size="small" @click="handleDelete(scope.row)"
                                           icon="el-icon-delete" class="delete-btn">删除
                                </el-button>
                                <el-button
                                    type="success"
                                    size="small"
                                    @click="handleStateChange(scope.row)"
                                    :style="{ backgroundColor: scope.row.state === 0 ? 'red' : '#67c23a' }"
                                >{{ scope.row.state === 0 ? '隐藏' : '显示' }}
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pageSize"
                        layout="total, prev, pager, next"
                        :total="total"
                    />
                </el-tab-pane>

                <el-tab-pane label="权限组" name="roles">
                    <div class="table-header">
                        <div class="table-title">权限组列表</div>
                        <div class="table-actions">
                            <el-button type="primary" @click="handleAddRole" size="small" icon="el-icon-plus">
                                添加权限组
                            </el-button>
                        </div>
                    </div>
                    <el-table height="560" :data="groupList" border style="width: 100%;overflow-y: auto"
                              :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                        <el-table-column prop="name" label="权限组"/>
                        <el-table-column prop="description" label="描述权限"/>
                        <el-table-column label="操作" width="300">
                            <template slot-scope="scope">
                                <!-- 编辑按钮，当scope.row.name不是"顶级分类"时显示 -->
                                <el-button v-if="scope.row.name!== '顶级分类'" type="text" size="small"
                                           @click="handleEditRole(scope.row)"
                                           icon="el-icon-edit">编辑
                                </el-button>
                                <!-- 删除按钮，当scope.row.name不是"顶级分类"时显示 -->
                                <el-button v-if="scope.row.name!== '顶级分类'" type="text" size="small"
                                           @click="handleDeleteRole(scope.row)"
                                           icon="el-icon-delete" class="delete-btn">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <!-- 添加/编辑管理员对话框 -->
            <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="登录名" prop="name">
                        <el-input v-model="adminForm.name"/>
                    </el-form-item>
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="adminForm.username"/>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="adminForm.password"/>
                        <span v-if="dialogTitle === '编辑管理员'" class="tip-text">密码为空则不修改</span>
                    </el-form-item>
                    <el-form-item label="权限组" prop="group_id">
                        <el-select v-model="adminForm.group_id" placeholder="请选择权限组">
                            <el-option
                                v-for="item in groupList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" prop="state">
                        <el-radio-group v-model="adminForm.state">
                            <el-radio :label="1">启用</el-radio>
                            <el-radio :label="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false" size="small">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="small">确定</el-button>
                </div>
            </el-dialog>

            <!-- 添加/编辑权限组对话框 -->
            <el-dialog :title="roleDialogTitle" :visible.sync="roleDialogVisible" width="500px"
                       :close-on-click-modal="false">
                <el-form :model="roleForm" :rules="roleRules" ref="roleForm" label-width="100px" size="small">
                    <el-form-item label="父级分类" prop="pid">
                        <el-select v-model="roleForm.pid" placeholder="请选择父级分类" @change="handleSelectChange">
                            <el-option
                                key="0"
                                label="顶级分类"
                                value="0"
                            />
                            <el-option
                                v-for="item in groupList.filter(item => item.name !== '顶级分类')"
                                :key="item.id"
                                :label="item.name"
                                :value="String(item.id)"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="权限组名称" prop="name">
                        <el-input v-model="roleForm.name" placeholder="请输入权限组名称"/>
                    </el-form-item>
                    <el-form-item label="权限配置">
                        <div class="tree-container"
                             style="height: 300px; overflow-y: auto; border: 1px solid #DCDFE6; border-radius: 4px; padding: 10px;">
                            <el-tree
                                :data="filteredPermissionTree"
                                show-checkbox
                                node-key="id"
                                ref="permissionTree"
                                :props="defaultProps"
                                :default-expand-all="true"
                                :check-strictly="true"
                                style="background: transparent;"
                            />
                        </div>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="roleDialogVisible = false" size="small">取消</el-button>
                    <el-button type="primary" @click="submitRoleForm" size="small">确定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
export default {
    computed: {
        // 过滤掉"顶级分类"节点
        filteredPermissionTree() {
            return this.filterTopCategory(this.permissionTree);
        }
    },
    data() {
        return {
            groupList: [],
            activeTab: 'admin',
            adminList: [],
            roleList: [],
            currentPage: 1,
            pageSize: 25,
            total: 0,
            dialogVisible: false,
            dialogTitle: '',
            adminForm: {
                name: '',
                username: '',
                password: '',
                group_id: '',
                state: 1
            },
            showButtonText: {},
            adminRules: {
                name: [{required: true, message: '请输入登录名', trigger: 'blur'}],
                username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
                group_id: [{required: true, message: '请选择权限组', trigger: 'change'}]
            },
            roleDialogVisible: false,
            roleDialogTitle: '',
            roleForm: {
                name: '',
                pid: '',
                level: '',
                state: 1,
                rules: [],
                pid_level: '0_0'  // 设置默认值
            },
            roleRules: {
                name: [{required: true, message: '请输入权限组名称', trigger: 'blur'}],
                pid: []
            },
            permissionTree: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            }
        };
    },
    mounted() {
        this.getGroup().then(() => {
            this.fetchAdminList();
        });
        this.fetchRoleList();
        this.fetchPermissionTree();
    },
    methods: {
        formatTimestamp(timestamp) {
            const date = new Date(timestamp * 1000); // 秒级时间戳转毫秒级
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hour = String(date.getHours()).padStart(2, '0');
            const minute = String(date.getMinutes()).padStart(2, '0');
            const second = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        },
        filterTopCategory(nodes) {
            if (!nodes) return [];
            return nodes.filter(node => {
                // 排除当前节点名为"顶级分类"
                if (node[this.defaultProps.label] === '顶级分类') return false;
                // 递归处理子节点（如果有）
                if (node[this.defaultProps.children]) {
                    node[this.defaultProps.children] = this.filterTopCategory(node[this.defaultProps.children]);
                }
                return true;
            });
        },
        getGroup() {
            return this.$http.get('/admin/AuthGroup/lists').then(result => {
                console.log(result)
                if (result.code === 200) {
                    this.groupList = result.data;
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        getGroupName(groupId) {
            const group = this.groupList.find(item => item.id === groupId);
            return group ? group.name : '超级管理员';
        },
        // 获取管理员列表
        fetchAdminList() {
            const params = {
                page: this.currentPage,
                limit: this.pageSize
            };
            console.log(params)
            this.$http.get('/admin/admin/lists', {params}).then(result => {
                if (result.code === 200) {
                    // 直接使用返回的data数组，假设接口返回的结构是 { data: [], total: number }
                    this.adminList = result.data.data;
                    this.total = result.data.total;
                    // 初始化按钮状态，state为0时显示'隐藏'
                    this.adminList.forEach(item => {
                        this.showButtonText[item.id] = item.state === 0;
                        if (item.children) {
                            item.children.forEach(child => {
                                this.showButtonText[child.id] = child.state === 0;
                            });
                        }
                    });
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        // 获取权限组列表
        fetchRoleList() {
            // TODO: 调用接口获取权限组列表
        },
        // 获取权限树
        fetchPermissionTree() {
            // this.$http.get('/admin/AuthNode/lists').then(result => {
            this.$http.get('/admin/AuthNode/listsNew', {}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data;
                    const treeArray = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            treeArray.push(dataObj[key]);
                        }
                    }
                    // 修正 children
                    function ensureChildrenArray(nodes) {
                        if (!Array.isArray(nodes)) return;
                        nodes.forEach(node => {
                            if (!Array.isArray(node.children)) {
                                node.children = [];
                            } else {
                                ensureChildrenArray(node.children);
                            }
                        });
                    }
                    ensureChildrenArray(treeArray);
                    this.permissionTree = treeArray;
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        // 分页相关方法
        handleSizeChange(val) {
            this.pageSize = val;
            this.currentPage = 1; // 切换每页显示数量时，重置当前页为第一页
            this.fetchAdminList();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchAdminList();
        },
        // 管理员相关方法
        handleAddAdmin() {
            this.dialogTitle = '添加管理员';
            this.adminForm = {
                name: '',
                username: '',
                password: '',
                group_id: '',
                state: 1
            };
            this.$refs.adminForm && this.$refs.adminForm.clearValidate();
            this.adminRules.password = [{required: true, message: '请输入密码', trigger: 'blur'}];
            this.dialogVisible = true;
        },
        handleEdit(row) {
            this.dialogTitle = "编辑管理员"
            // 调用接口获取详细数据
            this.$http.get(`/admin/admin/edit`, {params: {id: row.id}}).then(result => {
                if (result.code == 200) {
                    this.adminForm.name = result.data.name;
                    this.adminForm.username = result.data.username;
                    this.adminForm.password = ""
                    this.adminForm.group_id = result.data.group_id;
                    this.adminForm.state = result.data.state;
                    this.adminForm.id = result.data.id;
                    // 初始化详情图数组
                    this.detailImages = [];
                    // 打开编辑对话框
                    this.dialogVisible = true;

                    // 编辑时设置密码为非必填
                    this.adminRules.password = [{required: false, message: '请输入密码', trigger: 'blur'}];

                    // 等待 DOM 更新后设置表单验证状态
                    this.$nextTick(() => {
                        this.$refs.adminForm && this.$refs.adminForm.clearValidate();
                    });
                } else {
                    this.$message.error(result.msg || '获取详情失败');
                }
            }).catch(error => {
                console.error('获取详情失败:', error);
                this.$message.error('获取详情失败');
            });
        },
        handleDelete(row) {
            this.$confirm('确认删除该管理员?', '提示', {
                type: 'warning'
            }).then(() => {
                this.$http.post('/admin/admin/del', {...row, state: -1}).then(result => {
                    if (result.code == 200) {
                        this.$message.success(result.msg);
                        this.fetchAdminList();
                    } else {
                        this.$message.error(result.msg);
                    }
                });
            });
        },
        handleStateChange(row) {
            const newState = row.state === 1 ? 0 : 1;
            this.$http.post('/admin/admin/edit', {...row, state: newState}).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            });
        },

        submitForm() {
            console.log(this.adminForm)
            this.$refs.adminForm.validate(valid => {
                if (valid) {
                    this.$http.post('/admin/admin/edit', this.adminForm).then(result => {
                        if (result.code == 200) {
                            this.$message.success(result.msg);
                            this.dialogVisible = false;
                            this.fetchAdminList()
                        } else {
                            this.$message.error(result.msg);
                        }
                    });

                }
            });
        },
        // 权限组相关方法
        handleAddRole() {
            this.roleDialogTitle = '添加权限组';
            this.roleForm = {
                name: '',
                pid: '',
                level: '',
                state: 1,
                rules: [],
                pid_level: '0_0'  // 设置默认值
            };
            this.$nextTick(() => {
                if (this.$refs.roleForm) {
                    this.$refs.roleForm.clearValidate();
                }
                if (this.$refs.permissionTree) {
                    this.$refs.permissionTree.setCheckedKeys([]);
                }
            });
            this.roleDialogVisible = true;
        },
        handleSelectChange(value) {
            if (!value && value !== '0') {  // 处理清除的情况
                this.roleForm.pid = '0';
                this.roleForm.level = '0';
                this.roleForm.pid_level = '0_0';
                return;
            }

            if (value === '0') {  // 处理选择顶级分类的情况
                this.roleForm.pid = '0';
                this.roleForm.level = '0';
                this.roleForm.pid_level = '0_0';
                return;
            }

            const selectedItem = this.groupList.find(item => String(item.id) === value);
            if (selectedItem) {
                this.roleForm.pid = String(selectedItem.id);
                this.roleForm.level = selectedItem.level;
                this.roleForm.pid_level = `${selectedItem.id}_${selectedItem.level}`;
            }
        },

        handleEditRole(row) {
            console.log(row)
            this.roleDialogTitle = '编辑权限组';
            this.$http.get(`/admin/AuthGroup/edit`, {params: {id: row.id}}).then(result => {
                if (result.code === 200) {
                    const {name, pid, level, state, rules} = result.data;
                    const parsedRules = rules ? rules.split(',').map(Number).filter(Number.isFinite) : [];

                    this.roleForm = {
                        name,
                        pid: String(pid),  // 转换为字符串类型以匹配el-option的value类型
                        level,
                        state,
                        rules: parsedRules,
                        id: row.id,
                        pid_level: `${pid}_${level}`
                    };

                    this.$nextTick(() => {
                        if (this.$refs.roleForm) {
                            this.$refs.roleForm.clearValidate();
                        }
                        if (this.$refs.permissionTree && parsedRules.length > 0) {
                            this.$refs.permissionTree.setCheckedKeys(parsedRules);
                        }
                    });
                    this.roleDialogVisible = true;
                } else {
                    this.$message.error(result.msg || '获取详情失败');
                }
            }).catch(error => {
                console.error('获取详情失败:', error);
                this.$message.error('获取详情失败');
            });
        },
        handleDeleteRole(row) {
            this.$confirm('确认删除该权限组?', '提示', {
                type: 'warning'
            }).then(() => {
                this.$http.post('/admin/AuthGroup/del', {...row, state: -1}).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.getGroup();
                    } else {
                        this.$message.error(result.msg);
                    }
                });
            });
        },
        handleRoleStateChange(row) {
            const newState = row.state === 1 ? 0 : 1;
            const [pid, level] = (row.pid_level || '').split('_');
            this.$http.post('/admin/AuthGroup/edit', {
                ...row,
                state: newState,
                pid_level: row.pid_level || `${pid}_${level}`
            }).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                    this.getGroup();
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            });
        },

     submitRoleForm() {
    if (!this.$refs.roleForm) {
        this.$message.error('表单验证失败，请检查必填项');
        return;
    }

    // 构建提交的数据
    const submitData = {
        ...this.roleForm,
        pid_level: `${this.roleForm.pid}_${this.roleForm.level || '0'}`
    };

    // 如果没有选择父级分类，设置默认值
    if (!submitData.pid || submitData.pid === '') {
        submitData.pid = '0';
        submitData.level = '0';
        submitData.pid_level = '0_0';
    }

    this.$refs.roleForm.validate(valid => {
        if (valid) {
            try {
                let checkedKeys = this.$refs.permissionTree ? this.$refs.permissionTree.getCheckedKeys() : [];
                // 新增：把所有父节点也加入 checkedKeys
                const tree = this.permissionTree;
                const allKeys = new Set(checkedKeys);

                function addParentKeys(nodes, parentKey = null) {
                    nodes.forEach(node => {
                        if (checkedKeys.includes(node.id) && parentKey !== null) {
                            allKeys.add(parentKey);
                        }
                        if (node.children && node.children.length > 0) {
                            addParentKeys(node.children, node.id);
                        }
                    });
                }
                addParentKeys(tree);

                submitData.rules = Array.from(allKeys).map(Number).filter(key => !isNaN(key)).join(",");
                submitData.state = submitData.state || 1;

                const url = '/admin/AuthGroup/edit';
                this.$http.post(url, submitData).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.roleDialogVisible = false;
                        this.getGroup();
                    } else {
                        this.$message.error(result.msg || '操作失败');
                    }
                }).catch(error => {
                    console.error('请求失败:', error);
                    this.$message.error('网络请求失败，请检查网络连接');
                });
            } catch (error) {
                console.error('表单提交错误:', error);
                this.$message.error('表单提交出错，请重试');
            }
        }
    });
}

    },
    watch: {
        // 移除 roleForm 的 watch
    }
};
</script>

<style lang="less" scoped>
/deep/ .el-dialog__header {
    padding: 10px !important;
    text-align: center;
}

.admin-page {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);

    .page-header {
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #f0f2f5;

        .header-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.4;
        }
    }

    .table-header {
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table-title {
            font-size: 16px;
            font-weight: 500;
            color: #374151;
        }

        .table-actions {
            .el-button {
                margin-left: 12px;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }

    .el-tabs {
        margin-top: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 28px;
            border-bottom: 2px solid #f0f2f5;
        }

        :deep(.el-tabs__item) {
            font-size: 15px;
            padding: 0 28px;
            height: 44px;
            line-height: 44px;
            transition: all 0.3s;

            &.is-active {
                color: #2563eb;
                font-weight: 500;
            }

            &:hover {
                color: #2563eb;
            }
        }

        :deep(.el-tabs__active-bar) {
            height: 2px;
            background-color: #2563eb;
            transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
        }
    }

    .el-table {
        margin-top: 12px;
        border-radius: 8px;
        overflow: hidden;

        :deep(th) {
            background-color: #f9fafb !important;
            font-weight: 500;
            color: #4b5563;
        }

        :deep(td) {
            padding: 12px 0;
        }

        .delete-btn {
            color: #dc2626;
            transition: all 0.3s;

            &:hover {
                color: #ef4444;
            }
        }
    }

    .el-pagination {
        margin-top: 24px;
        padding: 12px 0;
        text-align: right;

        :deep(.el-pagination__total) {
            margin-right: 12px;
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
            border-radius: 4px;
            background-color: #fff;
        }

        :deep(.el-pager li) {
            border-radius: 4px;
            background-color: #fff;

            &.active {
                background-color: #2563eb;
            }
        }
    }

    .el-dialog {
        border-radius: 12px;
        overflow: hidden;
        max-height: 90vh;
        display: flex;
        flex-direction: column;

        :deep(.el-dialog__header) {
            padding: 20px 24px !important;
            border-bottom: 1px solid #f0f2f5;
            margin: 0;

            .el-dialog__title {
                font-size: 18px;
                font-weight: 600;
                color: #1f2937;
            }
        }

        :deep(.el-dialog__body) {
            padding: 32px 24px;
            flex: 1;
            overflow-y: auto;

            .el-form-item {
                .el-input,
                .el-select {
                    width: 320px;
                }
            }
        }

        :deep(.el-tree) {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #DCDFE6;
            border-radius: 4px;
            padding: 10px;
        }

        :deep(.el-dialog__footer) {
            padding: 16px 24px;
            border-top: 1px solid #f0f2f5;
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #374151;
        }

        :deep(.el-button) {
            padding: 8px 20px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-1px);
            }
        }
    }
}

.tip-text {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    display: block;
}

/deep/ .el-tab-pane {
    height: 650px;
    overflow-y: auto;
}

</style>
